using System.Linq;

namespace BCTLLC.UmbracoExtensions
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Collections;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Xml;
    using System.Xml.XPath;
    using umbraco.editorControls;
    using umbraco.presentation.nodeFactory;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Net.Mail;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    ///		Summary description for umbInputOutput.
    /// </summary>
    public partial class Doc2Form : System.Web.UI.UserControl
    {

        #region Default Controls
        protected PlaceHolder PHEditFields = new PlaceHolder();
        protected Panel PanelInput = new Panel();
        protected Panel PanelThanks = new Panel();
        protected Literal LiteralThanks = new Literal();
        protected Button btnPrevious = new Button();
        protected Button btnNext = new Button();
        protected Button btnSubmit = new Button();
        protected UpdatePanel up = new UpdatePanel();
        protected TextBox Title = new TextBox();
        #endregion

        #region Private Variables

        // Display option variables.
        private bool _editMode = false;
        private bool _showTitle = false;
        private string _titleName = "#title";
        private string _required = "#required";
        private string _thanks = "#thanks";
        private bool enableClientScript = true;
        private string _storeInCookie = "";
        private bool _pageTabs = false;
        private bool _hideTabNames = false;
        private bool _noSave = false;
        private string _dictRequired = "";
        private string _dictInvalid = "";
        private bool _useAjax = false;
        private string _defaultNode = null;
        private ArrayList _dataFields = new ArrayList();

        private string _insertBefore = "";
        private string _insertAfter = "";

        // umbraco document type variables.
        private string _nodeType;
        private string _template;
        private string _tabName = "";
        private int _nodeId = -20;
        private bool _publish = true;
        private bool _showDescription = false;
        private string _saveMemberIdAlias = "";
        private int _redirectNode = 0;
        private bool _refreshToParent = false;
        private int _userId = 0;

        // Generation variables.
        private umbraco.cms.businesslogic.web.Document d = null;

        // Email related fields.
        private bool _emailResponse = false;
        private string _responseSubject = "";
        private string _responseMessage = "";
        private string _emailField = "";
        private string _emailResponseTo = "";
        private string _responseCopyTo = "";

        private bool _emailForm = false;
        private string _formSubject = "";
        private string _formCustomMessage = "";
        private string _formMessage = "";
        private string _formToAddress = umbraco.UmbracoSettings.NotificationEmailSender;
        private string _formFromAddress = umbraco.UmbracoSettings.NotificationEmailSender;
        private string _formFromName = "";
        private string _formFromSenderAddress = "";
        private string _formReplyToAddress = "";

        private string _btnSubmit = "#submit";
        private string _btnNext = "#next";
        private string _btnPrevious = "#previous";

        // Database Settings
        private string _dbConnectionKey = "";
        private bool _dbSaveToExternal = false;
        private string _dbTable = "";

        private string _redirectAltTemplate = "";

        #endregion

        #region Public Properties
        [umbraco.cms.businesslogic.macro.MacroComment("Choose the Document type that you wish to be created")]
        public string DocumentType
        {
            set { _nodeType = value; }
        }
        public string Template
        {
            set { _template = value; }
        }
        public string TabName
        {
            set { _tabName = value; }
        }
        public bool PageTabs
        {
            set { _pageTabs = value; }
        }
        public bool HideTabNames
        {
            set { _hideTabNames = value; }
        }
        public int ChooseWhereToStore
        {
            set { _nodeId = value; }
        }
        public bool EditMode
        {
            set { _editMode = value; }
        }
        public bool ShowTitle
        {
            set { _showTitle = value; }
        }
        public string TitleName
        {
            set { _titleName = value; }
        }
        public string SaveMemberAlias
        {
            set { _saveMemberIdAlias = value; }
        }
        public bool ShowDescriptions
        {
            set { _showDescription = value; }
        }
        public string SubmitButtonText
        {
            set { _btnSubmit = value; }
        }
        public string NextButtonText
        {
            set { _btnNext = value; }
        }
        public string PreviousButtonText
        {
            set { _btnPrevious = value; }
        }
        public string RequiredText
        {
            set { _required = value; }
        }
        public string TextOnSubmit
        {
            set { _thanks = value; }
        }
        public bool PublishOnSubmit
        {
            set { _publish = value; }
        }
        public bool RefreshToParent
        {
            set { _refreshToParent = value; }
        }
        public int RedirectToNode
        {
            set { _redirectNode = value; }
        }
        public int PublishWithUserId
        {
            set { _userId = value; }
        }
        public string StorePropertiesInCookies
        {
            set { _storeInCookie = value; }
        }
        public bool EmailForm
        {
            set { _emailForm = value; }
        }
        public bool SendEmailResponse
        {
            set { _emailResponse = value; }
        }
        public string ResponseSubject
        {
            set { _responseSubject = value; }
        }
        public string ResponseMessage
        {
            set { _responseMessage = value; }
        }
        public string ResponseCopyTo
        {
            set { _responseCopyTo = value; }
        }
        public string ResponseEmailFieldAlias
        {
            set { _emailField = value; }
        }
        public string FormToEmailAddress
        {
            set { _formToAddress = value; }
        }
        public string FormFromEmailAddress
        {
            set { _formFromAddress = value; }
        }
        public string FormFromEmailName
        {
            set { _formFromName = value; }
        }
        public string FormFromEmailSenderAddress
        {
            set { _formFromSenderAddress = value; }
        }
        public string FormSubject
        {
            set { _formSubject = value; }
        }
        public string FormMessage
        {
            set { _formCustomMessage = value; }
        }
        public string DictRequired
        {
            set { _dictRequired = value; }
        }
        public string DictInvalid
        {
            set { _dictInvalid = value; }
        }
        public bool UseAjax
        {
            set { _useAjax = value; }
        }
        public string DefaultValueNode
        {
            set { _defaultNode = value; }
        }
        public string DbConnectionKey
        {
            set { _dbConnectionKey = value; }
        }
        public bool DbSaveToExternalTable
        {
            set { _dbSaveToExternal = value; }
        }
        public string DbTable
        {
            set { _dbTable = value; }
        }
        public string InsertBefore
        {
            set { _insertBefore = value; }
        }
        public string InsertAfter
        {
            set { _insertAfter = value; }
        }
        public string FormReplyToEmailAddress
        {
            set { _formReplyToAddress = value; }
        }

        public string RedirectAltTemplate
        {
            set { _redirectAltTemplate = value; }
        }
        #endregion

        #region Life Cycle Code
        private void InitializeComponent()
        {
            this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
            this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
            this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
        }
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //

            InitializeComponent();
            base.OnInit(e);

            BuildMainControls();
            SetValues();

            string userControlId = PanelInput.Parent.ClientID + "_";
            string fieldsets = string.Empty;
            int fieldSetCount = 0;

            if (_nodeId > 0)
                d = new umbraco.cms.businesslogic.web.Document(_nodeId);

            ValidationSummary vs = new ValidationSummary();
            vs.ID = "VS";
            vs.ShowSummary = true;
            vs.CssClass = "vsummary";
            vs.EnableClientScript = enableClientScript;

            if (_insertBefore.Length > 0) PHEditFields.Controls.Add(new LiteralControl(_insertBefore));

            PHEditFields.Controls.Add(vs);

            umbraco.cms.businesslogic.web.DocumentType ddt = null;
            try
            {
                ddt = new umbraco.cms.businesslogic.web.DocumentType(Int32.Parse(_nodeType));
            }
            catch
            {
                try
                {
                    ddt = umbraco.cms.businesslogic.web.DocumentType.GetByAlias(_nodeType);
                }
                catch
                {
                    Response.Write("Error loading document type.");
                    return;
                }
            }
            //Get Defaults, if used...
            ArrayList defaultNodes = new ArrayList();
            if (!_editMode && _defaultNode != null)
                foreach (string defaultDocId in _defaultNode.Split(";".ToCharArray()))
                {
                    // TODO: Interpret properties...  - Work around to umbraco macro defaults
                    try
                    {
                        umbraco.cms.businesslogic.web.Document doc = new umbraco.cms.businesslogic.web.Document(Int32.Parse(defaultDocId));
                        defaultNodes.Add(doc);
                    }
                    catch { }
                }
            //Each selected tab
            foreach (umbraco.cms.businesslogic.ContentType.TabI t in ddt.getVirtualTabs)
            {
                if (("," + _tabName.Replace(", ", ",") + ",").IndexOf("," + t.Caption.ToLower() + ",") > -1)
                {
                    PlaceHolder ph = new PlaceHolder();
                    ph.ID = "fs" + fieldSetCount.ToString();
                    ph.EnableViewState = true;

                    PHEditFields.Controls.Add(ph);

                    fieldSetCount++;
                    ph.Controls.Add(new LiteralControl("<fieldset id=\"fs_" + t.Id.ToString() + "\">"));

                    if (!_hideTabNames)
                        ph.Controls.Add(new LiteralControl("<legend>" + t.Caption + "</legend>"));

                    ph.Controls.Add(new LiteralControl("<ol>"));

                    if (_required.Length > 0)
                        ph.Controls.Add(new LiteralControl("<li class=\"required required_li\"><label><strong>" + _required + "</strong></label></li>"));

                    // Title
                    if (_showTitle && fieldSetCount == 1)
                    {
                        if (d != null && _editMode)
                            Title.Text = d.Text;

                        Title.ID = "Title";
                        ph.Controls.Add(new LiteralControl("<li class=\"required title_li\"><label for=\"" + Title.ClientID + "\"><strong>" + _titleName + "</strong></label>"));
                        ph.Controls.Add(Title);
                        RequiredFieldValidator rq = new RequiredFieldValidator();
                        rq.ID = Title.ID + "_RFV";
                        rq.ControlToValidate = Title.ID;
                        rq.EnableClientScript = enableClientScript;
                        rq.Display = System.Web.UI.WebControls.ValidatorDisplay.None;
                        string[] errorVars = { _titleName, "" };
                        if (_dictRequired.Length > 0)
                            rq.ErrorMessage = string.Format(_dictRequired, _titleName);
                        else
                            rq.ErrorMessage = umbraco.ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null);
                        ph.Controls.Add(rq);
                        ph.Controls.Add(new LiteralControl("</li>"));
                    }
                    // Properties on current tab
                    foreach (umbraco.cms.businesslogic.propertytype.PropertyType pt in t.PropertyTypes)
                    {
                        umbraco.interfaces.IDataType dt = pt.DataTypeDefinition.DataType;

                        dt.DataEditor.Editor.ID = pt.Alias;
                        _dataFields.Add(dt);

                        umbraco.interfaces.IData df = pt.DataTypeDefinition.DataType.Data;

                        ph.Controls.Add(new LiteralControl("<li class=\"" + pt.DataTypeDefinition.DataType.DataTypeName.Replace(" ", "").ToLower() + (pt.Mandatory ? " required " : " ") + dt.DataEditor.Editor.ClientID + "_li\">"));


                        ph.Controls.Add(new LiteralControl("<label for=\"" + userControlId + dt.DataEditor.Editor.ClientID
                            + "\">"
                            + (pt.Mandatory ? "<strong>" + pt.Name + "</strong>" : pt.Name) + "</label>"));

                        // Load Default Values...
                        if (!_editMode && _defaultNode != null)
                        {
                            try
                            {
                                foreach (umbraco.cms.businesslogic.web.Document doc in defaultNodes)
                                    if (doc.getProperty(dt.DataEditor.Editor.ID).Value != null)
                                    {
                                        dt.Data.Value = doc.getProperty(dt.DataEditor.Editor.ID).Value;
                                        break;
                                    }
                            }
                            catch { }
                        }
                        // Load edit properties
                        if (_nodeId > 0 && _editMode)
                        {
                            dt.Data.PropertyId = d.getProperty(dt.DataEditor.Editor.ID).Id;
                            dt.Data.Value = d.getProperty(dt.DataEditor.Editor.ID).Value;
                        }
                        // Load stored settings from Cookies
                        if (!_editMode && _storeInCookie != "")
                        {
                            if (System.Web.HttpContext.Current.Request.Cookies["Doc2Form" + dt.DataEditor.Editor.ID] != null)
                                if (System.Web.HttpContext.Current.Request.Cookies["Doc2Form" + dt.DataEditor.Editor.ID].Value != "")
                                    try
                                    {
                                        dt.Data.Value = System.Web.HttpContext.Current.Request.Cookies["Doc2Form" + dt.DataEditor.Editor.ID].Value;
                                    }
                                    catch { }
                        }

                        ph.Controls.Add(dt.DataEditor.Editor);

                        // Validation
                        if (pt.Mandatory)
                        {
                            try
                            {
                                RequiredFieldValidator rq = new RequiredFieldValidator();
                                rq.ID = dt.DataEditor.Editor.ID + "_RFV";
                                rq.ControlToValidate = dt.DataEditor.Editor.ID;
                                rq.EnableClientScript = enableClientScript;
                                rq.Display = ValidatorDisplay.None;
                                string[] errorVars = { pt.Name, "" };
                                if (_dictRequired.Length > 0)
                                    rq.ErrorMessage = string.Format(_dictRequired, pt.Name);
                                else
                                    rq.ErrorMessage = umbraco.ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null);
                                ph.Controls.Add(rq);
                            }
                            catch (Exception valE)
                            {
                                System.Web.HttpContext.Current.Trace.Warn("AutoForm", "EditorControl (" + dt.DataTypeName + " : " + dt.DataEditor.Editor.ID + ") does not support validation", valE);
                            }
                        }
                        // RegExp Validation
                        if (pt.ValidationRegExp != "")
                        {
                            try
                            {
                                RegularExpressionValidator rv = new RegularExpressionValidator();
                                rv.ID = dt.DataEditor.Editor.ID + "_REV";
                                rv.ControlToValidate = dt.DataEditor.Editor.ID;
                                rv.ValidationExpression = pt.ValidationRegExp;
                                rv.EnableClientScript = enableClientScript;
                                rv.Display = ValidatorDisplay.None;
                                string[] errorVars = { pt.Name, "" };
                                if (_dictInvalid.Length > 0)
                                    rv.ErrorMessage = string.Format(_dictInvalid, pt.Name);
                                else
                                    rv.ErrorMessage = umbraco.ui.Text("errorHandling", "errorRegExpWithoutTab", errorVars, null);
                                ph.Controls.Add(rv);
                            }
                            catch (Exception valE)
                            {
                                System.Web.HttpContext.Current.Trace.Warn("AutoForm", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE);
                            }
                        }
                        if (_showDescription && pt.Description != "")
                        {
                            if (pt.Description.StartsWith("#"))
                                ph.Controls.Add(new LiteralControl("<p>" + umbraco.library.GetDictionaryItem(pt.Description.Substring(1)) + "</p>"));
                            else
                                ph.Controls.Add(new LiteralControl("<p>" + pt.Description + "</p>"));
                        }
                        ph.Controls.Add(new LiteralControl("</li>"));
                    }
                    ph.Controls.Add(new LiteralControl("</ol></fieldset>"));
                }
            }
            if (_insertAfter.Length > 0) PHEditFields.Controls.Add(new LiteralControl(_insertAfter));

            ViewState.Add("fieldSetCount", fieldSetCount);
            ViewState.Add("currentFieldSet", 0);

            if (!IsPostBack)
            {
                if (_pageTabs == true && fieldSetCount > 1)
                    buttons(0);
                else
                    btnSubmit.Visible = true;
            }
        }
        private void BuildMainControls()
        {
            if (_useAjax && ScriptManager.GetCurrent(Page) != null)
            {
                up.ContentTemplateContainer.Controls.Add(PanelInput);
                up.ContentTemplateContainer.Controls.Add(PanelThanks);
                this.Controls.Add(up);
            }
            else
            {
                this.Controls.Add(PanelInput);
                this.Controls.Add(PanelThanks);
            }

            PanelInput.Controls.Add(PHEditFields);
            PanelInput.Controls.Add(btnPrevious);
            PanelInput.Controls.Add(btnNext);
            PanelInput.Controls.Add(btnSubmit);


            PanelThanks.Controls.Add(new LiteralControl("<p>"));
            PanelThanks.Controls.Add(LiteralThanks);
            PanelThanks.Controls.Add(new LiteralControl("</p>"));

            PanelInput.CssClass = "Doc2Form";
            PanelThanks.Visible = false;
            PanelThanks.CssClass = "Doc2Form PanelThanks";
            btnPrevious.Visible = false;
            btnPrevious.CssClass = "button";
            btnPrevious.CausesValidation = false;
            btnNext.Visible = false;
            btnNext.CssClass = "button";
            btnSubmit.Visible = false;
            btnSubmit.CssClass = "button";
        }
        private void SetValues()
        {
            if (_nodeId == -20)
            { // if the node has not been set, then we will not save the results.
                _noSave = true;
            }

            if (_thanks.Length > 1)
                if (_thanks.StartsWith("#"))
                    _thanks = umbraco.library.GetDictionaryItem(_thanks.Substring(1));
            if (_thanks.Length > 1)
                LiteralThanks.Text = _thanks;

            if (_responseMessage.Length > 1)
                if (_responseMessage.StartsWith("#"))
                    _responseMessage = umbraco.library.GetDictionaryItem(_responseMessage.Substring(1));

            if (_responseSubject.Length > 1)
                if (_responseSubject.StartsWith("#"))
                    _responseSubject = umbraco.library.GetDictionaryItem(_responseSubject.Substring(1));

            if (_responseMessage.Length > 1)
                if (_responseMessage.StartsWith("#"))
                    _responseMessage = umbraco.library.GetDictionaryItem(_responseMessage.Substring(1));

            if (_responseCopyTo.Length > 1)
                if (_responseCopyTo.StartsWith("#"))
                    _responseCopyTo = umbraco.library.GetDictionaryItem(_responseCopyTo.Substring(1));

            if (_formSubject.Length > 1)
                if (_formSubject.StartsWith("#"))
                    _formSubject = umbraco.library.GetDictionaryItem(_formSubject.Substring(1));

            if (_formCustomMessage.Length > 1)
                if (_formCustomMessage.StartsWith("#"))
                    _formCustomMessage = umbraco.library.GetDictionaryItem(_formCustomMessage.Substring(1));

            if (_formToAddress.Length > 1)
                if (_formToAddress.StartsWith("#"))
                    _formToAddress = umbraco.library.GetDictionaryItem(_formToAddress.Substring(1));

            if (_formFromAddress.Length > 1)
                if (_formFromAddress.StartsWith("#"))
                    _formFromAddress = umbraco.library.GetDictionaryItem(_formFromAddress.Substring(1));

            if (_required.Length > 1)
                if (_required.StartsWith("#"))
                    _required = umbraco.library.GetDictionaryItem(_required.Substring(1));

            if (_titleName.Length > 1)
                if (_titleName.StartsWith("#"))
                    _titleName = umbraco.library.GetDictionaryItem(_titleName.Substring(1));

            if (_btnSubmit.Length > 1)
                if (_btnSubmit.StartsWith("#"))
                    _btnSubmit = umbraco.library.GetDictionaryItem(_btnSubmit.Substring(1));
            if (_btnSubmit.Length > 1)
                btnSubmit.Text = _btnSubmit;

            if (_btnPrevious.Length > 1)
                if (_btnPrevious.StartsWith("#"))
                    _btnPrevious = umbraco.library.GetDictionaryItem(_btnPrevious.Substring(1));
            if (_btnPrevious.Length > 1)
                btnPrevious.Text = _btnPrevious;

            if (_btnNext.Length > 1)
                if (_btnNext.StartsWith("#"))
                    _btnNext = umbraco.library.GetDictionaryItem(_btnNext.Substring(1));
            if (_btnNext.Length > 1)
                btnNext.Text = _btnNext;

            if (_dictRequired.Length > 1)
            {
                if (_dictRequired.StartsWith("#"))
                    _dictRequired = umbraco.library.GetDictionaryItem(_dictRequired.Substring(1));
                else
                    _dictRequired = umbraco.library.GetDictionaryItem(_dictRequired);
            }

            if (_dictInvalid.Length > 1)
            {
                if (_dictInvalid.StartsWith("#"))
                    _dictInvalid = umbraco.library.GetDictionaryItem(_dictInvalid.Substring(1));
                else
                    _dictInvalid = umbraco.library.GetDictionaryItem(_dictInvalid);
            }

            if (_insertBefore.Length > 1)
                if (_insertBefore.StartsWith("#"))
                    _insertBefore = umbraco.library.GetDictionaryItem(_insertBefore.Substring(1));

            if (_insertAfter.Length > 1)
                if (_insertAfter.StartsWith("#"))
                    _insertAfter = umbraco.library.GetDictionaryItem(_insertAfter.Substring(1));
        }
        #endregion

        #region Button Methods
        private void btnSubmit_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                umbraco.cms.businesslogic.web.Document d; //null;

                // Variables for 3rd Party Database Table support.
                SqlConnection connDB = new SqlConnection();
                SqlCommand cmdSelect = new SqlCommand();
                SqlCommand cmdUpdate = new SqlCommand();
                Hashtable sqlParam = new Hashtable();
                string strUpdate = "";
                SqlDataReader dr;


                if (_dbSaveToExternal)
                {
                    if (_dbConnectionKey == "")
                        connDB.ConnectionString = umbraco.GlobalSettings.DbDSN;
                    else if (ConfigurationSettings.AppSettings[_dbConnectionKey] != null)
                        connDB.ConnectionString = ConfigurationSettings.AppSettings[_dbConnectionKey].ToString();

                    connDB.Open();
                    cmdSelect.Connection = connDB;
                }

                if (!_editMode)
                {
                    umbraco.cms.businesslogic.CMSNode parent = new umbraco.cms.businesslogic.CMSNode(_nodeId);
                    string text = Title.Text;
                    if (!_showTitle && text.Length == 0)
                    {
                        try
                        {
                            text = "RE: " + parent.Text;
                        }
                        catch
                        {
                            text = "Created by Doc2Form on " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
                        }
                    }
                    umbraco.cms.businesslogic.web.DocumentType ddt = null;
                    try
                    {
                        ddt = new umbraco.cms.businesslogic.web.DocumentType(Int32.Parse(_nodeType));
                    }
                    catch
                    {
                        try
                        {
                            ddt = umbraco.cms.businesslogic.web.DocumentType.GetByAlias(_nodeType);
                        }
                        catch { }
                    }
                    d = umbraco.cms.businesslogic.web.Document.MakeNew(text, ddt, new umbraco.BusinessLogic.User(_userId), _nodeId);

                    // External Database
                    // Save ID

                    if (_dbSaveToExternal)
                    {
                        //try
                        //{
                        cmdSelect.CommandText = @"SELECT * FROM [" + _dbTable + "] WHERE 1=0";  // Get Table Schema.
                        strUpdate = "INSERT INTO [" + _dbTable + "] ( %1 ) VALUES ( %2 )";
                        //}
                        //catch { }
                    }
                }
                else
                {
                    d = new umbraco.cms.businesslogic.web.Document(_nodeId);
                    if (_showTitle)
                        d.Text = Title.Text;

                    // External Database
                    if (_dbSaveToExternal)
                    {
                        try
                        {
                            cmdSelect.CommandText = @"SELECT * FROM [" + _dbTable + "] WHERE 1=0";  // Get Table Schema.
                            strUpdate = "UPDATE " + _dbTable + " SET %1=%2";
                        }
                        catch { }
                    }
                }

                // Template Fields : ID
                _responseMessage = _responseMessage.Replace("[ID]", d.Id.ToString());
                _formCustomMessage = _formCustomMessage.Replace("[ID]", d.Id.ToString());
                _responseSubject = _responseSubject.Replace("[ID]", d.Id.ToString());
                _formSubject = _formSubject.Replace("[ID]", d.Id.ToString());

                //try
                //{
                if (_dbSaveToExternal)
                {
                    dr = cmdSelect.ExecuteReader();
                    for (int i = 0; i < dr.VisibleFieldCount; i++)
                    {
                        //Response.Write(i.ToString() + "-id-");
                        if (dr.GetName(i).ToLower() == "id")
                        {
                            if (_editMode)
                                strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "]").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ", %1=%2");
                            else
                                strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "],%1").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ",%2");

                            sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(i).ToLower().Replace(" ", "_"), d.Id));
                            break;
                        }
                    }
                }
                else
                {
                    dr = null;
                }
                //}
                //catch { }


                if (_showTitle)
                    _formMessage += "-".PadRight(80, Char.Parse("-")) + "\n" + _titleName.ToString() + " : " + d.Text + "\n";// + "-".PadRight(80, Char.Parse("-")) + "\n";

                // Template Fields : Title
                _responseMessage = _responseMessage.Replace("[Title]", d.Text);
                _formCustomMessage = _formCustomMessage.Replace("[Title]", d.Text);
                _responseSubject = _responseSubject.Replace("[Title]", d.Text);
                _formSubject = _formSubject.Replace("[Title]", d.Text);

                // External Database Save
                //try
                //{
                if (_dbSaveToExternal)
                {
                    for (int i = 0; i < dr.VisibleFieldCount; i++)
                    {
                        //Response.Write(i.ToString() + "-title-");
                        if (dr.GetName(i).ToLower() == "title")
                        {
                            if (_editMode)
                                strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "]").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ", %1=%2");
                            else
                                strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "],%1").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ",%2");

                            sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(i).ToLower().Replace(" ", "_"), d.Text));
                            break;
                        }
                    }
                }
                //}
                //catch { }

                // Save properties
                foreach (umbraco.interfaces.IDataType df in _dataFields)
                {
                    df.Data.PropertyId = d.getProperty(df.DataEditor.Editor.ID).Id;
                    df.DataEditor.Save();

                    try
                    {
                        if (_emailForm || _dbSaveToExternal)
                        {
                            try
                            {
                                // Look for prevalue entries.
                                if (((KeyValuePrevalueEditor)df.PrevalueEditor).Prevalues.Keys.Count > 0)
                                {
                                    string preVal = string.Empty;

                                    foreach (string val in df.Data.Value.ToString().Split(",".ToCharArray()))
                                    {
                                        int key = Int32.Parse(val.Trim());

                                        if (((KeyValuePrevalueEditor)df.PrevalueEditor).Prevalues.ContainsKey(val))
                                            preVal += "\n" + ((KeyValuePrevalueEditor)df.PrevalueEditor).Prevalues[val].ToString();
                                        else
                                            preVal += "\n" + val + "";
                                    }

                                    if (preVal.Replace("\n", "").Trim() == "") preVal = df.Data.Value.ToString();

                                    // Template Fields
                                    _formMessage += "-".PadRight(80, Char.Parse("-")) + "\n" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Name.ToString() + " : " + preVal + "\n";// + "-".PadRight(80, Char.Parse("-")) + "\n";
                                    _responseMessage = _responseMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));
                                    _formCustomMessage = _formCustomMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));
                                    _responseSubject = _responseSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));
                                    _formSubject = _formSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));

                                    _formToAddress = _formToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));
                                    _formFromAddress = _formFromAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));
                                    _formReplyToAddress = _formReplyToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));

                                    _emailResponseTo = _emailResponseTo.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", preVal.Replace("\n", ", ").Substring(2));

                                    // External Database Save
                                    //try
                                    //{
                                    if (_dbSaveToExternal)
                                    {
                                        for (int i = 0; i < dr.VisibleFieldCount; i++)
                                        {
                                            //Response.Write(i.ToString() + "-" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower() + "-");
                                            if (dr.GetName(i).ToLower() == d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower())
                                            {
                                                if (_editMode)
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "]").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ", %1=%2");
                                                else
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "],%1").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ",%2");

                                                sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(i).ToLower().Replace(" ", "_"), preVal));
                                                break;
                                            }
                                        }
                                    }
                                    //}
                                    //catch { }
                                }
                            }
                            catch
                            {
                                if (df.Data.Value.ToString().IndexOf("\n") > -1 | df.Data.Value.ToString().Length > 39)
                                {
                                    // Template Fields
                                    _formMessage += "-".PadRight(80, Char.Parse("-")) + "\n" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Name.ToString() + ":\n" + df.Data.Value.ToString() + "\n";// + "-".PadRight(80, Char.Parse("-")) + "\n";
                                    _responseMessage = _responseMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formCustomMessage = _formCustomMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _responseSubject = _responseSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formSubject = _formSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    _formToAddress = _formToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formFromAddress = _formFromAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formReplyToAddress = _formReplyToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    _emailResponseTo = _emailResponseTo.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    // External Database Save
                                    //try
                                    //{
                                    if (_dbSaveToExternal)
                                    {

                                        for (int i = 0; i < dr.VisibleFieldCount; i++)
                                        {
                                            //Response.Write(i.ToString() + "-" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower() + "-");
                                            if (dr.GetName(i).ToLower() == d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower())
                                            {
                                                if (_editMode)
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "]").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ", %1=%2");
                                                else
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "],%1").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ",%2");

                                                sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(i).ToLower().Replace(" ", "_"), df.Data.Value.ToString()));
                                                break;
                                            }
                                        }
                                    }
                                    //}
                                    //catch { }
                                }
                                else
                                {
                                    // Template Fields
                                    _formMessage += "-".PadRight(80, Char.Parse("-")) + "\n" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Name.ToString().PadRight(39, char.Parse(" ")) + " : " + df.Data.Value.ToString() + "\n";
                                    _responseMessage = _responseMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formCustomMessage = _formCustomMessage.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _responseSubject = _responseSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formSubject = _formSubject.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    _formToAddress = _formToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formFromAddress = _formFromAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());
                                    _formReplyToAddress = _formReplyToAddress.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    _emailResponseTo = _emailResponseTo.Replace("[" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToString() + "]", df.Data.Value.ToString());

                                    // External Database Save
                                    //try
                                    //{		
                                    if (_dbSaveToExternal)
                                    {

                                        for (int i = 0; i < dr.VisibleFieldCount; i++)
                                        {
                                            //Response.Write(i.ToString() + "-" + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower() + "-");
                                            if (dr.GetName(i).ToLower() == d.getProperty(df.DataEditor.Editor.ID).PropertyType.Alias.ToLower())
                                            {
                                                if (_editMode)
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "]").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ", %1=%2");
                                                else
                                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(i) + "],%1").Replace("%2", "@" + dr.GetName(i).ToLower().Replace(" ", "_") + ",%2");

                                                sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(i).ToLower().Replace(" ", "_"), df.Data.Value.ToString()));
                                                break;
                                            }
                                        }
                                    }
                                    //}
                                    //catch { }
                                }
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        Trace.Warn("Doc2Form", "Error writing email form message.  " + d.getProperty(df.DataEditor.Editor.ID).PropertyType.Name.ToString(), ee);
                    }


                    if ((", " + _emailField + ", ").IndexOf(", " + df.DataEditor.Editor.ID + ", ") > -1)
                    {
                        try
                        {
                            _emailResponseTo = df.Data.Value.ToString();
                        }
                        catch (Exception ee)
                        {
                            Trace.Warn("Doc2Form", "Error reading email address from form fields.", ee);
                        }
                    }

                    if ((", " + _storeInCookie + ", ").IndexOf(", " + df.DataEditor.Editor.ID + ", ") > -1)
                    {
                        try
                        {
                            System.Web.HttpCookie c = new System.Web.HttpCookie("Doc2Form" + df.DataEditor.Editor.ID, df.Data.Value.ToString());
                            c.Expires = DateTime.Now.AddYears(1);
                            System.Web.HttpContext.Current.Response.Cookies.Add(c);
                        }
                        catch (Exception ee)
                        {
                            Trace.Warn("Doc2Form", "Error storing value in cookie:" + df.DataEditor.Editor.ID, ee);
                        }
                    }
                }
                // Save Server Variables...
                for (int i = 0; i < Request.ServerVariables.Count; i++)
                {
                    try
                    {
                        d.getProperty(Request.ServerVariables.GetKey(i)).Value = Request.ServerVariables[i].ToString();
                    }
                    catch { }

                    if (_dbSaveToExternal)
                    {

                        for (int y = 0; i < dr.VisibleFieldCount; i++)
                        {
                            if (dr.GetName(y).ToLower() == Request.ServerVariables.GetKey(i).ToLower())
                            {
                                if (_editMode)
                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(y) + "]").Replace("%2", "@" + dr.GetName(y).ToLower().Replace(" ", "_") + ", %1=%2");
                                else
                                    strUpdate = strUpdate.Replace("%1", "[" + dr.GetName(y) + "],%1").Replace("%2", "@" + dr.GetName(y).ToLower().Replace(" ", "_") + ",%2");

                                sqlParam.Add(sqlParam.Count, new SqlParameter("@" + dr.GetName(y).ToLower().Replace(" ", "_"), Request.ServerVariables[i].ToString()));
                                break;
                            }
                        }
                    }
                }

                if (_dbSaveToExternal)
                {
                    //try
                    //{
                    dr.Close();

                    if (connDB.State != ConnectionState.Open)
                    {
                        //       connDB.ConnectionString = 
                        connDB.Open();
                    }
                    cmdUpdate.Connection = connDB;
                    cmdUpdate.CommandText = strUpdate.Replace(",%1", "").Replace(",%2", "").Replace(", %1=%2", "");
                    for (int i = 0; i < sqlParam.Count; i++)
                    {
                        cmdUpdate.Parameters.Add((SqlParameter)sqlParam[i]);
                    }
                    //Response.Write(strUpdate.Replace(",%1", "").Replace(",%2", "").Replace(", %1=%2", ""));
                    cmdUpdate.ExecuteNonQuery();
                    //}
                    //catch { }
                }
                try
                {
                    if (connDB.State == ConnectionState.Open)
                        connDB.Close();
                    dr.Dispose();
                    connDB.Dispose();
                    cmdUpdate.Dispose();
                    cmdSelect.Dispose();
                }
                catch { }
                // Maybe save member info
                try
                {
                    if (_saveMemberIdAlias != "" && umbraco.cms.businesslogic.member.Member.GetCurrentMember() != null)
                        d.getProperty(_saveMemberIdAlias).Value = umbraco.cms.businesslogic.member.Member.GetCurrentMember().Id;
                }
                catch
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, d.User, d.Id, "Error saving member data. The specified Member Property alias ('" + _saveMemberIdAlias + "') does not exists on document type ('" + d.ContentType.Text + "').");
                }

                if (_template != "")
                {
                    try
                    { //try integer
                        d.Template = new umbraco.cms.businesslogic.template.Template(Int32.Parse(_template)).Id;
                    }
                    catch
                    { // try alias
                        try { d.Template = umbraco.cms.businesslogic.template.Template.GetByAlias(_template).Id; }
                        catch { }
                    }
                }

                if (!_noSave && _publish)
                {
                    d.Publish(new umbraco.BusinessLogic.User(_userId));
                    umbraco.library.UpdateDocumentCache(d.Id);
                }
                else if (!_noSave)
                    umbraco.BusinessLogic.Actions.Action.RunActionHandlers(d, umbraco.BusinessLogic.Actions.ActionUpdate.Instance);
                else
                {
                    d.delete(); // Delete from Recycling Bin.
                }

                if (_redirectNode == -1 && _nodeId != -1) //ChooseWhereToStore 
                    _redirectNode = _nodeId;
                else if (_redirectNode == -2 && !_noSave) //self
                    _redirectNode = d.Id;


                System.Uri uriMedia = new System.Uri(HttpContext.Current.Request.Url, "/media/", true);


                System.Uri uri = new System.Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.RawUrl, true);

                string url = uri.ToString() + "\nNode ID: " + d.Id + "\n\n";

                SmtpClient smtp = new SmtpClient();

                if (_emailForm)
                //try
                {
                    if (_formSubject.Length == 0)
                        _formSubject = "Doc2Form: " + umbraco.library.GetItem("nodeName").ToString();

                    if (_formCustomMessage.Length == 0)
                        _formCustomMessage = "Doc2Form from: [#URL] \n[#FORM]";

                    MailMessage mm = new MailMessage();
                    mm.From = _formFromName.Length > 0 ? new MailAddress(_formFromAddress, _formFromName) : new MailAddress(_formFromAddress);
                    mm.To.Add(new MailAddress(_formToAddress));
                    mm.Subject = ReplaceMacroParameters(ReplaceNodeProperties(_formSubject));
                    mm.Body = ReplaceMacroParameters(ReplaceNodeProperties(_formCustomMessage.Replace("[#URL]", url).Replace("[#FORM]", "<pre>" + _formMessage + "</pre>").Replace("/media/", uriMedia.ToString()).Replace("\n", "<br/>\n")));

                    mm.IsBodyHtml = true;
                    mm.BodyEncoding = Encoding.UTF8;

                    if (_formFromSenderAddress.Length > 0)
                        mm.Sender = _formFromName.Length > 0 ? new MailAddress(_formFromSenderAddress, _formFromName) : new MailAddress(_formFromSenderAddress);

                    if (_formReplyToAddress != "")
                        mm.ReplyTo = new MailAddress(_formReplyToAddress);

                    smtp.Send(mm);

                }
                //catch (Exception ee)
                //{
                //    Trace.Warn("Doc2Form", "Error sending form email.", ee);
                //}

                if (_emailResponse && _emailResponseTo.Length > 0)
                //try
                {

                    MailMessage mm = new MailMessage();
                    mm.From = _formFromName.Length > 0 ? new MailAddress(_formFromAddress, _formFromName) : new MailAddress(_formFromAddress);
                    mm.To.Add(new MailAddress(_emailResponseTo));
                    mm.Subject = ReplaceMacroParameters(_responseSubject.Length > 0 ? _responseSubject : "Confirmation" + " : " + umbraco.library.GetItem("nodeName"));
                    mm.Body = ReplaceMacroParameters(_responseMessage.Replace("[#URL]", url).Replace("[#FORM]", "<pre>" + _formMessage + "</pre>").Replace("/media/", uriMedia.ToString()).Replace("\n", "<br/>\n"));
                    mm.IsBodyHtml = true;
                    mm.BodyEncoding = Encoding.UTF8;

                    if (_formFromSenderAddress.Length > 0)
                    {
                        mm.From = _formFromName.Length > 0 ? new MailAddress(_formFromSenderAddress, _formFromName) : new MailAddress(_formFromSenderAddress);
                        mm.Sender = _formFromName.Length > 0 ? new MailAddress(_formFromAddress, _formFromName) : new MailAddress(_formFromAddress);
                    }

                    if (_responseCopyTo.Length > 0)
                        mm.Bcc.Add(new MailAddress(_responseCopyTo));
                    smtp.Send(mm);
                }
                //catch (Exception ee)
                //{
                //    Trace.Warn("Doc2Form", "Error sending form email.", ee);
                //}

                // Update UI
                if (_redirectNode > 1)
                {
                    Response.Redirect(umbraco.library.NiceUrl(_redirectNode) + '/' + _redirectAltTemplate, true);
                }
                else if (_refreshToParent)
                {
                    Response.Redirect(umbraco.library.NiceUrl(_nodeId) + '/' + _redirectAltTemplate, true);
                }
                else
                {
                    PanelInput.Visible = false;
                    PanelThanks.Visible = true;
                }
            }
        }
        private void btnPrevious_Click(object sender, System.EventArgs e)
        {
            buttons(-1);
        }
        private void btnNext_Click(object sender, System.EventArgs e)
        {
            buttons(+1);
        }
        private void buttons(int val)
        {
            int fieldSetCount = Int32.Parse(ViewState["fieldSetCount"].ToString());
            int currentFieldSet = Int32.Parse(ViewState["currentFieldSet"].ToString());

            if (val > 0)
            {
                Page.Validate();
                if (Page.IsValid || val == -1)
                {
                    if ((val == 1 && currentFieldSet < fieldSetCount - 1) || (val == -1 && currentFieldSet > 0))
                        currentFieldSet += val;
                }
            }
            else if (val == -1)
                if ((val == 1 && currentFieldSet < fieldSetCount - 1) || (val == -1 && currentFieldSet > 0))
                    currentFieldSet += val;


            ViewState["currentFieldSet"] = currentFieldSet;

            for (int i = 0; i < fieldSetCount; i++)
                ((PlaceHolder)this.FindControl("fs" + i.ToString())).Visible = false;//.Style.Add("display","none");

            ((PlaceHolder)this.FindControl("fs" + currentFieldSet.ToString())).Visible = true;//.Style.Add("display", "block");

            btnNext.Visible = (currentFieldSet < fieldSetCount - 1);
            btnPrevious.Visible = (currentFieldSet > 0);
            btnSubmit.Visible = (currentFieldSet == fieldSetCount - 1);
        }
        #endregion

        #region Helper Classes
        private string ReplaceMacroParameters(string str)
        {
            str = ReplaceNodeProperties(str);
            str = ReplaceQueryStringParameters(str);
            str = ReplaceCookieValues(str);

            return str;
        }
        private string ReplaceNodeProperties(string str)
        {
            // Get current page
            Node n = Node.GetCurrent();

            // Replace Node Id
            str = str.Replace("[#pageID]", n.Id.ToString());

            // Replace Parent Node Id
            str = str.Replace("[#parentID]", n.Parent.Id.ToString());

            // Replace Level
            str = str.Replace("[#level]", n.Path.Count(curChar => Char.Parse(",") == curChar).ToString());

            // Replace Writer Id
            str = str.Replace("[#writerID]", n.WriterID.ToString());

            // Replace Node Type Id
            str = str.Replace("[#nodeType]", umbraco.library.GetXmlNodeById(n.Id.ToString()).Current.GetAttribute("nodeType", ""));

            // Replace Template
            str = str.Replace("[#template]", n.template.ToString());

            // Replace Node Creation Date
            str = str.Replace("[#createDate]", n.CreateDate.ToShortDateString() + " " + n.CreateDate.ToShortTimeString());

            // Replace Node Update Date
            str = str.Replace("[#updateDate]", n.UpdateDate.ToShortDateString() + " " + n.UpdateDate.ToShortTimeString());

            // Replace Node Name
            str = str.Replace("[#pageName]", n.Name);

            // Replace Node Url Name
            str = str.Replace("[#urlName]", n.Url.Substring(n.Url.LastIndexOf("/") + 1, n.Url.Substring(n.Url.LastIndexOf("/")).Length - 5));

            // Replace Writer Name
            str = str.Replace("[#writerName]", n.WriterName);

            // Replace Node Type Alias
            str = str.Replace("[#nodeTypeAlias]", n.NodeTypeAlias);

            // Replace Node Path
            str = str.Replace("[#path]", n.Path);

            // Replace Full Url
            str = str.Replace("[#fullUrl]", Request.Url.AbsoluteUri);

            // Replace custom properties
            foreach (Property p in n.Properties)
            {
                str = str.Replace("[#" + p.Alias + "]", p.Value);
            }

            return str;
        }
        private string ReplaceQueryStringParameters(string str)
        {
            // Replace querystring parameters
            foreach (string key in Request.QueryString.Keys)
            {
                if (Request.QueryString[key] != null)
                {
                    str = str.Replace("[@" + key + "]", Request.QueryString[key]);
                }
            }

            return str;
        }
        private string ReplaceCookieValues(string str)
        {
            // Replace cookie values
            foreach (string key in Request.Cookies.Keys)
            {
                if (Request.Cookies[key] != null)
                {
                    str = str.Replace("[%" + key + "]", Request.Cookies[key].Value);
                }
            }

            return str;
        }
        #endregion
    }
}
